package com.pansoft.openplanet.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AlertDialog;

import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.core.xml.StubObject;
import com.efounder.activity.AbActivity;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.event.SystemInitOverEvent;
import com.efounder.chat.http.GetHttpUtil;
import com.efounder.chat.http.OpenPlanetFriendUserRequestUtil;
import com.efounder.chat.model.NoticeCountEvent;
import com.efounder.chat.model.UpdateBadgeViewEvent;
import com.efounder.chat.model.UpdateResEvent;
import com.efounder.chat.service.MessageService;
import com.efounder.chat.service.OSPService;
import com.efounder.chat.service.SystemInfoService;
import com.efounder.chat.service.WatchService;
import com.efounder.chat.utils.CommonThreadPoolUtils;
import com.efounder.chat.utils.RSAUtil;
import com.efounder.chat.utils.ServiceUtils;
import com.efounder.chat.widget.BadgeView;
import com.efounder.common.floatwindow.FloatWindowService;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.forwechat.BaseApp;
import com.efounder.fragment.LeftDrawerFragment;
import com.efounder.fragment.MenuFragment.RefreshforDefineMenu;
import com.efounder.fragment.PagerSlidingTab2Fragment;
import com.efounder.fragment.PagerSlidingTabFragment;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.frame.utils.Constants;
import com.efounder.interfaces.BadgeUtil;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.model.APKUpdateManager;
import com.efounder.model.ClearBadgeEvent;
import com.efounder.model.RESUpdateManager;
import com.efounder.model.RefreshViewEvent;
import com.efounder.service.Registry;
import com.efounder.skin.CustomSDCardLoader;
import com.efounder.util.AbFragmentManager;
import com.efounder.util.LogOutUtil;
import com.efounder.util.MenuGnqxUtil;
import com.efounder.util.MyStaticWebView;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.efounder.view.titlebar.AbBottomBar;
import com.efounder.widget.EFImage;
import com.efounder.widget.ESPWebView;
import com.efounder.widget.TabBarNew;
import com.efounder.widget.TabBarNew.OnCurrentTabChangedListener;
import com.pansoft.kline.helper.BtcKanConfigAndRateHelper;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.fragment.AdvertisingDialogFragment;
import com.pansoft.openplanet.fragment.OpenPlanetMainFragment;
import com.pansoft.openplanet.util.AssetsCompareLocalWithServerManager;
import com.pansoft.openplanet.util.SyncImUserManager;
import com.pansoft.openplanet.util.TCAccountManager;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.pansoft.resmanager.ResLoadManager;
import com.pansoft.start.LoginCheckManager;
import com.pansoft.xmlparse.OptionParser;
import com.tencent.bugly.crashreport.CrashReport;
import com.utilcode.util.AppUtils;
import com.utilcode.util.LogUtils;
import com.utilcode.util.ReflectUtils;
import com.utilcode.util.SizeUtils;
import com.zhuiji7.filedownloader.download.DownLoadService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.File;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;

import q.rorbin.badgeview.QBadgeView;
import skin.support.SkinCompatManager;

import static com.efounder.chat.model.Constant.SKIN_DIR;
import static com.efounder.frame.utils.Constants.CHAT_PASSWORD;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;


/**
 * 底部 activity
 */
@SuppressWarnings("unused")
public class TabBottomActivityForTalkChain extends AbActivity implements
        OnCurrentTabChangedListener, RefreshforDefineMenu {

    /**
     * 记录按下返回键的时间
     */
    private long firstime;
    private List<StubObject> mainMenus; // 主菜单
    private List<StubObject> defaultMenus;
    public static final String KEY_MENU_ROOT = "menuRoot";
    private AbBottomBar mBottomBar;

    /**
     * 当前Tab页面索引
     */
    public int currentTab;


    private FragmentManager fm;

    static TabBottomActivityForTalkChain mySelf;
    private Fragment preprocessedFrag;
    /**
     * 底部按钮是否正在显示状态
     */
    private boolean isShowing;
    private TabBarNew tb;
    public static final String TAG = "TabBottomActivityTC";


    private BaseFragment willShowFragment;
    private BaseFragment willHideFragment;

    //    private int currentIndex = 0;
//
    private TabBottomActivityResultListener onTabBottomActivityResultListener;
    private int unReadmessageNum = 0;
    private long systemCurrentTime;

    public BaseFragment[] cachedFragments; // 缓存主菜单对应的Fragments
    //微信聊天id 和password
    private String chatUserID;
    private String chatPassword;

    //private ProgressDialog progressDialog;
    private int RecordClickNumFortry = 1;
    private APKUpdateManager apkUpdateManager = new APKUpdateManager();

    //线程锁
    final Object synObj = new Object();
    //反射的push推送相关
    private ReflectUtils reflectPushManager;


    public static void start(Context context) {
        Intent starter = new Intent(context, TabBottomActivityForTalkChain.class);
        starter.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        context.startActivity(starter);
    }


    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //bugly设置登录用户id,这样我们可以知道哪个用户闪退
        CrashReport.setUserId(EnvironmentVariable.getUserName());

        //FIXME 注册文件夹
        long time1 = System.currentTimeMillis();
        Registry.init(ResLoadManager.getTabMenuPath());
        long time2 = System.currentTimeMillis();

//        Log.e("yqs1", time2 - time1 + "");


        //设置不可滑动返回
        getSwipeBackLayout().setEnableGesture(false);
        //2.XXX-为activity注册的默认 音频通道 。
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        setAbContentView(R.layout.tab_bottom_n);


        chatUserID = EnvironmentVariable.getProperty(CHAT_USER_ID, "");
        chatPassword = EnvironmentVariable.getProperty(CHAT_PASSWORD, "");


        BadgeUtil.initBadge();
        // 设置默认显示的标签页
        fm = getSupportFragmentManager();
        initView();
        String isLoadStaticWebView = EnvironmentVariable.getProperty("isLoadStaticWebView");
        if ((null != isLoadStaticWebView && !isLoadStaticWebView.equals("1"))) {
            initWebview();
        }

        getTitleBar().setVisibility(View.GONE);
        initData();
        initBadge();
        //注册监听
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }


        initImInfo();

        String username = EnvironmentVariable.getUserName();
        String password = EnvironmentVariable.getPassword();
        if (username == null) {
            try {
                ToastUtil.showToast(getApplicationContext(), ResStringUtil.getString(R.string.open_planet_tab_user_invalid));
                Intent intent = new Intent();
                intent.setClass(this, Class.forName("com.efounder.activity.Login_withTitle"));
//                stopAllService();
                LogOutUtil.stopLocalIMService(this);
                startActivity(intent);
                this.finish();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            return;
        }

        checkApkVersion();
        String loginType = EnvironmentVariable.getProperty("LoginType");

        //获取eth 用户信息并比对
        AssetsCompareLocalWithServerManager localWithServerManager = new AssetsCompareLocalWithServerManager(this);
        localWithServerManager.startCompare();

        //调用臧老师接口
        String isNewInstall = EnvironmentVariable.getProperty(EnvironmentVariable.getUserName() + "IsNewInstall", "0");
        if (!isNewInstall.equals("1")) {
//            sendOnlineMessage();
        }
        //兼容操作
        compatOpration();
        //请求币看配置信息
        BtcKanConfigAndRateHelper.initConfig();
        //首页弹窗
        AdvertisingDialogFragment.showAdvertisingDialogFragment();
        long time3 = System.currentTimeMillis();

//        Log.e("yqs1", time3 - time2 + "");

    }

    /**
     * 初始化im的相关信息
     */
    private void initImInfo() {
        CommonThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {

                            int newFriendCount = WeChatDBManager.getInstance().getNewFriendUnread();
                            int groupNoticeCount = WeChatDBManager.getInstance().getGroupNoticveUnreadCount();
                            EventBus.getDefault().post(new NoticeCountEvent(newFriendCount, groupNoticeCount));
                            getImUserInfo();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });


    }

    /**
     * 发送在线消息
     */
    private void sendOnlineMessage() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                HashMap<String, String> map = new HashMap<>();
                map.put("access_token", EnvironmentVariable.getProperty("tc_access_token"));
                TCRequestUtil.getCommonRequest(TAG, "user/onLineMessage", map, new TCRequestUtil.TCRequestCallback() {
                    @Override
                    public void onSuccess(String response) {
                        EnvironmentVariable.setProperty(EnvironmentVariable.getUserName() + "IsNewInstall", "1");
                        Log.i(TAG, response + "sendOnlineMessage");
                    }

                    @Override
                    public void onFail(String error) {
                        Log.i(TAG, error + "errorsendOnlineMessage");
                    }
                });
            }
        }, 3000);

    }


    private void sendToServer(final String address, final String publicKey) {
        if (address.equals("") || publicKey.equals("")) {
            return;
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("access_token", EnvironmentVariable.getProperty("tc_access_token"));
        map.put("ethAddress", address);
        map.put("ethPublicKey", publicKey);
        map.put("comPublicKey", EnvironmentVariable.getProperty(RSAUtil.getCurrentPublicKey()));

        TCRequestUtil.postOAuthRequest(TAG, "user/updateUserEthPublicKeyAndAddress", map,
                new TCRequestUtil.TCRequestCallback() {
                    @Override
                    public void onSuccess(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (jsonObject.has("result")
                                    && jsonObject.getString("result")
                                    .equals("success")) {

                            } else {
                            }
                        } catch (Exception e) {
                        }
                    }

                    @Override
                    public void onFail(String error) {

                    }
                });
    }

    /**
     * 检查APK版本
     */
    public void checkApkVersion() {
        if (!getIntent().hasExtra("unDoCheck")) {
//            LoginByRestFul loginByRestFul = new LoginByRestFul(1);
//            loginByRestFul.loginBegin(TabBottomActivityForTalkChain.this, "", "");
            LoginCheckManager loginCheckManager = new LoginCheckManager(this);
            loginCheckManager.checkVersionAfterLogin(LoginCheckManager.TYPE_NOT_LOGIN);
        }
    }

    //获取im用户好友以以及群组信息
    private void getImUserInfo() throws Exception {
        //非第一次请求
        if (EnvironmentVariable.getProperty(EnvironmentVariable.getProperty(CHAT_USER_ID) + "tcfirstrequest", "true").equals("false")) {
            GetHttpUtil.getUserInfo(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)),
                    TabBottomActivityForTalkChain.this, new GetHttpUtil.GetUserListener() {
                        @Override
                        public void onGetUserSuccess(User user) {
                            if (user == null) {
                                return;
                            }
                            EnvironmentVariable.setProperty(Constants.KEY_NICK_NAME, user.getNickName());
                        }

                        @Override
                        public void onGetUserFail() {

                        }
                    });
            OpenPlanetFriendUserRequestUtil.getFriendData(this, null);
            GetHttpUtil.getGroupListByLoginId(this, null);
            GetHttpUtil.getAllOfficialNumber(this);
        } else {
            //第一次请求 需要弹出
            SyncImUserManager manager = new SyncImUserManager(this);
            manager.requestServer();
        }
    }

    //保存eth 星际通讯相关数据
    private void insertUserEth() {
        String ethAddress = EnvironmentVariable.getProperty("tc_ethAddress", "");
        String ethPublicKey = EnvironmentVariable.getProperty("tc_ethPublicKey", "");
        String userJson = EnvironmentVariable.getProperty("tc_user_info", "");
        if (!userJson.equals("")) {
            net.sf.json.JSONObject userObject = net.sf.json.JSONObject.fromObject(userJson);
            User user = new User();
            user.setAvatar(userObject.optString("avatar", ""));
            user.setWalletAddress(userObject.optString("ethAddress", ""));
            user.setPublicKey(userObject.optString("ethPublicKey", ""));
            user.setId(userObject.optInt("imUserId"));
            user.setNickName(userObject.optString("nickName", ""));
            user.setSex(userObject.optString("sex", "M"));
            user.setSigNature(userObject.optString("sign", ""));
            //该json 的userid 是手机号 对应 im user的 name 字段
            user.setName(userObject.optString("userId", ""));
            user.setPhone("");
            user.setMobilePhone("");
            user.setEmail("");
            WeChatDBManager.getInstance().insertUserTable(user);
        }
    }

    private void initBadge() {
        if (null == mainMenus) {
            return;
        }
        //不在列表里显示角标
        String chatIdNotReachedByChatListItem = "";
        for (int i = 0; i < mainMenus.size(); i++) {
            if (i >= 5) {
                //最多只有五个菜单
                return;
            }
            StubObject stubObject = mainMenus.get(i);
            String id = (String) stubObject.getID();
            //配置文件是否该tab的角标可拖动
            boolean draggable = stubObject.getString("badgeDraggable", "false").equals("true");

            List chatIDs = BadgeUtil.badgeMap.get(id);

            int unReadCount = BadgeUtil.getCount(id);

            EFImage efImage = tb.getImageList().get(i);
            //设置角标的id和是否拖动
            efImage.setNodeId(id, draggable);
            if (efImage.getBadgeView() == null) {
                QBadgeView badgeView = new QBadgeView(TabBottomActivityForTalkChain.this);
                badgeView.bindTarget(efImage);
                efImage.setNodeId(id, draggable);
                efImage.initBadgeView(badgeView);
            }
            efImage.setBadgeCount(unReadCount);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 1, sticky = true)
    public void onSolveMessageEvent(SystemInitOverEvent event) {
        BadgeUtil.initBadge();
        initBadge();
        ((BaseApp) getApplicationContext()).setSystemInited(true);

    }

    //清除角标
    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onClearBadgeEvent(ClearBadgeEvent event) {
        BadgeUtil.clearBadge(event.getNodeId());

    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 1)
    public void onSolveMessageEvent(UpdateBadgeViewEvent event) {
        int fromUserId = Integer.parseInt(event.getUserID());
        byte chatType = event.getChatType();
        boolean mustRefresh = event.isRefreshAll();
        Long a1 = System.currentTimeMillis();
        for (int i = 0; i < mainMenus.size(); i++) {
            StubObject stubObject = mainMenus.get(i);
            String id = (String) stubObject.getID();
            //配置文件是否该tab的角标可拖动
            boolean draggable = stubObject.getString("badgeDraggable", "false").equals("true");
//            Long a3 = System.currentTimeMillis();

            List chatIDs = BadgeUtil.badgeMap.get(id);
            if (!mustRefresh) {
                if (!BadgeUtil.isNeedRefreshBadge(chatIDs, fromUserId, chatType)) {
                    continue;
                }
            }
            int unReadCount = BadgeUtil.getCount(id);
//            Long a4 = System.currentTimeMillis();
//            Log.i("xxxxxxxxa4-a3",a4-a3+"");

            EFImage efImage = tb.getImageList().get(i);
            if (efImage.getBadgeView() == null) {
                QBadgeView badgeView = new QBadgeView(TabBottomActivityForTalkChain.this);
                badgeView.bindTarget(efImage);
                efImage.setNodeId(id, draggable);
                efImage.initBadgeView(badgeView);
            }
            efImage.setBadgeCount(unReadCount);

//            Long a5 = System.currentTimeMillis();
//            Log.i("xxxxxxxxa5-a4",a5-a4+"");

        }
//        Long a2 = System.currentTimeMillis();
//        Log.i("xxxxxxxxa2-a1",a2-a1+"");

        int totalUnReadNum = 0;
        for (int i = 0; i < mainMenus.size(); i++) {
            EFImage efImage = tb.getImageList().get(i);
            int badgeNum = efImage.getBadgeCount();
            totalUnReadNum += badgeNum;
        }
        me.leolin.shortcutbadger.ShortcutBadger.applyCount(getApplicationContext(), totalUnReadNum);
    }

    @Deprecated
    private void updateBadge(int position) {
        String appIdArrayString = EnvironmentVariable.getProperty("Badge" + position, "");
        int unReadCount = 0;
        if (!appIdArrayString.equals("")) {

            String[] appIdArray = appIdArrayString.split(",");
            //过滤空字符串
            for (int j = 0; j < appIdArray.length; j++) {
                String appId = appIdArray[j];
                if (appId.equals("")) {
                    continue;
                }
            }
            for (int j = 0; j < appIdArray.length; j++) {
                String appId = appIdArray[j];
                if (appId.equals("")) {
                    continue;
                }
                int unRead = JFMessageManager.getInstance().getUnReadCount(Integer.parseInt(appId), (byte) 0);
                unReadCount += unRead;
            }
        } else {
            unReadCount = 0;
        }
        LinearLayout ll = (LinearLayout) ((LinearLayout) tb.getChildAt(1)).getChildAt(position);
        View v = ll.getChildAt(0);

        BadgeView badgeView = null;
        try {
            badgeView = tb.findViewWithTag("badge" + position);
        } catch (Exception e) {

        }

        if (badgeView == null) {

            return;
        }
        if (unReadCount > 99) {
            badgeView.setText("99+");
        } else {
            badgeView.setText(unReadCount + "");
        }

        me.leolin.shortcutbadger.ShortcutBadger.applyCount(TabBottomActivityForTalkChain.this, unReadCount);
        badgeView.setBadgeBackgroundColor(getResources().getColor(
                R.color.chat_red));
        if (unReadCount <= 0 && unReadCount != -1) {
            badgeView.setVisibility(View.INVISIBLE);
        } else {
            badgeView.show();
        }
    }

    /**
     * 初始化DrawerLayout
     */
    private void initDrawerLayout() {
        //设置允许打开左边抽屉
        getDrawerLayout().setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.LEFT);
        if (getSupportFragmentManager().findFragmentByTag("tag_LeftDrawerFragment") == null) {//避免出现划出左侧抽屉空白问题//if (savedInstanceState == null) {
            //设置左边抽屉Fragment
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(getDrawerLayoutLeftLayoutResId(), new LeftDrawerFragment(), "tag_LeftDrawerFragment").commit();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //初始化手机的push功能 获取token(反射实现)
        try {
            if (reflectPushManager == null) {
                reflectPushManager = ReflectUtils.reflect("com.efounder.push.PushManager").newInstance(this);
            }
            reflectPushManager.method("initPushTokenAndConnect");
            //清除小米push 角标
            reflectPushManager.method("clearPushNotification");
            //google FCM推送
            reflectPushManager.method("getFCMPushToken");
        } catch (Exception e) {
            LogUtils.e("PushManager初始化失败，可能不支持推送");
        }

        //！！！启动服务(再onResume中启动，防止这种情况：Activity处于前台，service先于Activity被回收掉)
        try {
            startService(new Intent(this, MessageService.class));

            if (!ServiceUtils.isServiceRunning(getApplicationContext(), SystemInfoService.class.getCanonicalName())) {
                String userID = EnvironmentVariable.getUserID();
                if (userID != null && !"".equals(userID)) {
                    startService(new Intent(this, SystemInfoService.class));
                }
            }
            if (!ServiceUtils.isServiceRunning(getApplicationContext(), OSPService.class.getCanonicalName())) {
                startService(new Intent(this, OSPService.class));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        //初始化悬浮窗服务
        initFloatWindow(false);
        initDrawerLayout();

    }


    private void initData() {
        mySelf = this;
        isShowing = true;
    }


    @Override
    public void onBackPressed() {
        if (fm.getBackStackEntryCount() != 0) {
            fm.popBackStack();
            return;
        }
        if (System.currentTimeMillis() - systemCurrentTime > 3000) {
            ToastUtil.showToast(getApplicationContext(), ResStringUtil.getString(R.string.open_planet_tab_one_back_home_again));
            systemCurrentTime = System.currentTimeMillis();
        } else {

            moveTaskToBack(false);
        }
    }

    private void initWebview() {
        if (true) {
            return;
        }
        // TODO Auto-generated method stub
        MyStaticWebView.newInstance(TabBottomActivityForTalkChain.this
                .getApplicationContext());
        //Log.i("TimeCheck","登录初始化webview所用时间————————"+(System.currentTimeMillis() - currentTime));
        MyStaticWebView.getWv().setJsToandroidCallBack(
                new ESPWebView.JsToandroidCallBack() {
                    @Override
                    public void html5initover() {
                    }
                });
        MyStaticWebView.getWv().setEspContext(this);
    }

    /**
     * 初始化UI
     */
    private void initView() {

        //加载配置文件
        if (mainMenus == null) {
//            mainMenuList = CommonMethodUtil.getTab_Menu_FromXml();
            mainMenus = getMain_Menu_FromXml();
        }

        makeMainMenu();
    }

    /**
     * 初始化UI
     */
    private void refreshView() {
        //加载配置文件
//        MenuList.clearRegistry();
        Registry.clearRegistry();
        OptionParser.getInstance().release();
//        mainMenuList = CommonMethodUtil.getTab_Menu_FromXml();
        mainMenus = null;
        initView();
        ////  除消息页和通讯录两页其他的角标
        BadgeUtil.initBadge();
        initBadge();
//        //控制消息页和通讯录两页的角标
//        initBadge2();
        //mainMenuList = getMain_Menu_FromXml();
        //makeMainMenu();

    }

    /**
     * 加载完主菜单之后调用, 生存主菜单布局
     */
    private void makeMainMenu() {
        if (mainMenus == null) {
            ToastUtil.showToast(getApplicationContext(), ResStringUtil.getString(R.string.common_text_http_request_data_fail));
            this.finish();
            return;
        }
        cachedFragments = new BaseFragment[mainMenus.size()];
        loadBottomBar(mainMenus);
    }

    private void loadBottomBar(List<StubObject> espMenuList) {
        tb = new TabBarNew(this, espMenuList);
        if (tb.getTopOutPosition() != -1) {
            this.changeNavigationHeight();
        }
        mBottomBar = this.getBottomBar();
        mBottomBar.removeAllViews();
        mBottomBar.setVisibility(View.VISIBLE);

        FrameLayout.LayoutParams tabParams = new FrameLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                SizeUtils.dp2px(50));
        tabParams.gravity = Gravity.BOTTOM;
        mBottomBar.addView(tb, tabParams);
        tb.setOnCurrentTabChangedListener(this);
        //旧方式加载fragment yqs

//        currentTab = inittab;
//        if (getIntent().hasExtra("shareToZone")) {
//            tb.setCurrentTab(1);
//            currentTab = 1;
//        }
//        willHideFragment = willShowFragment;
//        willShowFragment = initAndCacheFragment(currentTab);
//        showFragment(willShowFragment);
//        CheckUpdateHandler.sendEmptyMessage(6);


        //获取应用初始要展示的菜单index
        currentTab = getDefaultDisplayIndex();
        if (getIntent().hasExtra("shareToZone")) {
            tb.setCurrentTab(1);
            currentTab = 1;
        }
        showPageByIndex(currentTab);

//        showFragment(currentTab);
    }

    /**
     * 获取应用打开时，默认显示第几个tab页面
     * 目前是从配置文件读取，可以重写这个方法返回相应的index
     *
     * @return
     */
    protected int getDefaultDisplayIndex() {
        int defaultPosition = tb.getDefaultSelectedTab();
        return defaultPosition;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent.hasExtra("shareToZone")) {
            showFragment(1);
        }

    }

    @Override
    public void onCurrentTabChanged(int index) {
        RecordClickNumFortry++;
        //TODO 判断是否是试用版
        boolean isTRY = false;
        if (RecordClickNumFortry >= 5 && isTRY) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);  //先得到构造器
            builder.setTitle(R.string.common_text_hint); //设置标题
            builder.setMessage(ResStringUtil.getString(R.string.open_planet_tab_trial_version)); //设置内容
            builder.setIcon(R.drawable.wechat_icon_launcher);//设置图标，图片id即可
            builder.setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() { //设置确定按钮
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss(); //关闭dialog
                    // Toast.makeText(TabBottomActivity.this, "确认" + which, Toast.LENGTH_SHORT).show();
                }
            });
            //参数都设置完成了，创建并显示出来
            builder.create().show();
        }
        showPageByIndex(index);

    }

    private void showPageByIndex(int index) {
        StubObject mainMenuItem = mainMenus.get(index);
        String isActivity = mainMenuItem.getString("isActivity", "");
        // frag = com.efounder.util.AbFragmentManager.getFragment(mainMenuItem);
        if (isActivity.equals("true")) {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            Class<?> clazz = null;
            try {
                List<StubObject> subMenus = Registry.getRegEntryList((String) mainMenuItem.getID());
                Hashtable menuTable = mainMenuItem.getStubTable();
                StubObject stubObject = subMenus.get(0);
                String AndroidShow = stubObject.getString("AndroidShow", "");
                clazz = loader.loadClass(AndroidShow);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            if (clazz != null) {
                startActivity(new Intent(this, clazz));
            }
        } else {
            showFragment(index);
        }
    }

    public View getBottomView(int index) {
        View v = ((LinearLayout) tb.getChildAt(1)).getChildAt(index);

        View badge = tb.findViewWithTag("badge" + index);
        if (badge != null) {
//            System.out.println(".....判断badage..............." + index);
            ((ViewGroup) badge.getParent()).removeView(badge);
        }
        return v;
    }

    public void showFragment(int index) {
//        Log.i("", "test-----====================TabBottomActivityForTalkChain: onCurrentTabChanged:位置：" + index);
        // 缓存并显示fragment
        FragmentTransaction ft = obtainFragmentTransaction(index);
        if (cachedFragments[index] != null) { // 取缓存
            willShowFragment = cachedFragments[index];
        } else {
            willShowFragment = initAndCacheFragment(index);
            ft.add(R.id.mainContent, willShowFragment, index + "");
        }

        if (getCurrentFragment() != null) {
            getCurrentFragment().onPause(); // 暂停当前tab
        }
        if (willShowFragment.isAdded()) {
            willShowFragment.onStart(); // 启动目标tab的onStart()
        } else {
//                ft.add(R.id.mainContent, willShowFragment,index+"");
        }
        showTab(ft, index); // 显示目标tab


    }

    public Fragment getCurrentFragment() {
        return cachedFragments[currentTab];
    }


    /**
     * 创建并且缓存Fragment
     *
     * @param index
     */
    private BaseFragment initAndCacheFragment(int index) {
        BaseFragment frag = null;
        StubObject mainMenuItem = mainMenus.get(index);

        // frag = com.efounder.util.AbFragmentManager.getFragment(mainMenuItem);
        AbFragmentManager ab = new AbFragmentManager(this);
        // 根据viewtype的类型得到
        frag = ab.getFragment(mainMenuItem);

        frag.setBadgeType("" + index);
        cachedFragments[index] = frag; // 缓存
        frag.setAlone(false);

        return frag;
    }

    /**
     * 获取一个带动画的FragmentTransaction
     *
     * @param index
     * @return
     */
    private FragmentTransaction obtainFragmentTransaction(int index) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

        return ft;
    }


    /**
     * 切换TAB(先隐藏，后显示)
     *
     * @param
     * @param ft
     */
    private void showTab(FragmentTransaction ft, int index) {
//        FragmentTransaction ft = obtainFragmentTransaction(index);
        willShowFragment = cachedFragments[index];
        willHideFragment = cachedFragments[currentTab];
        if (willHideFragment != null && !willShowFragment.equals(willHideFragment)) {
            ft.hide(willHideFragment);
        }
        if (willShowFragment != null) {
            ft.show(willShowFragment);
        }
        //ft.commit();
        ft.commitAllowingStateLoss();
        currentTab = index; // 更新目标tab为当前tab
        tb.setCurrentTabColor(index);
        TabBarNew.mCurrentTabIndex = index;

        mBottomBar.onTabChanged(index);

    }

//    /**
//     * 显示fragment
//     */
//    public void showFragment(final Fragment frag) {
//        FragmentTransaction tra = fm.beginTransaction();
//        //tra.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
//        tra.add(R.id.mainContent, frag, frag.getClass().getName());
//        tra.commit();
//
//    }

    @Override
    protected void onPause() {
        super.onPause();
    }


    // ----------------提供接口--------------------
    public static TabBottomActivityForTalkChain getInstance() {
        return mySelf;
    }


    public void jumpAndStoreStack(Fragment frag) {
        if (frag == null) {
            return;
        }
        FragmentTransaction trasaction = fm.beginTransaction();
        trasaction.add(R.id.mainContent, frag, frag.getClass().getName());
        trasaction.addToBackStack(null);
        trasaction.commit();
    }

    public void popBackStack() {
        fm.popBackStack();
    }

    public TabBarNew getTb() {
        return tb;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        //防止被回收
        super.onSaveInstanceState(outState);
        outState.putSerializable("databack", (Serializable) mainMenus);

    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (mainMenus == null) {
            getMain_Menu_FromXml();
        }
    }

    public List<StubObject> getMain_Menu_FromXml() {
        mainMenus = Registry.getRegEntryList(KEY_MENU_ROOT);
        //初始化多语言的Menu
        ResLoadManager.loadMultiLanguageMenu();
        defaultMenus = Registry.getRegEntryList("DefaultOpenMenu");
        if (mainMenus == null && defaultMenus != null) {
            mainMenus = defaultMenus;
        }

        MenuGnqxUtil.handleGNQX(mainMenus);//处理功能权限

        return mainMenus;
    }

    @Override
    public void refreshNotice() {
        if (willShowFragment instanceof PagerSlidingTabFragment) {
            if (((PagerSlidingTabFragment) willShowFragment).getAdapter().getCurrentFragment() instanceof OpenPlanetMainFragment) {
                ((OpenPlanetMainFragment) ((PagerSlidingTabFragment) willShowFragment).getAdapter().getCurrentFragment()).refreshGrid();
            }
        }
        if (willShowFragment instanceof PagerSlidingTab2Fragment) {
            if (((PagerSlidingTab2Fragment) willShowFragment).getAdapter().getCurrentFragment() instanceof OpenPlanetMainFragment) {
                ((OpenPlanetMainFragment) ((PagerSlidingTab2Fragment) willShowFragment).getAdapter().getCurrentFragment()).refreshGrid();
            }
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
//        Log.i("", "-------onActivityResult:" + TAG);
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (onTabBottomActivityResultListener != null) {
                onTabBottomActivityResultListener.onTabBottomActivityResult(requestCode, resultCode, data);
            }
        } else if (resultCode == FloatWindowService.REQUEST_CODE_PERMISSON_OVERLAY) {
            //请求弹框权限
            initFloatWindow(true);
        }
    }

    private void initFloatWindow(boolean isOnactivityresult) {
        if (FloatWindowService.checkOverLayPermission(this, isOnactivityresult)) {
            FloatWindowService.startFloatService(this);
        }
    }

    public interface TabBottomActivityResultListener {
        void onTabBottomActivityResult(int requestCode, int resultCode, Intent data);
    }


    public void setOnTabBottomActivityResultListener(
            TabBottomActivityResultListener onTabBottomActivityResultListener) {
        this.onTabBottomActivityResultListener = onTabBottomActivityResultListener;
    }

    @Override
    protected void onStop() {
        super.onStop();
//        Log.w("--", TAG + "-----onStop--");
        // EFHttpRequest.cancelRequest(TAG);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        mySelf = null;
        BtcKanConfigAndRateHelper.release();
    }


    Handler CheckUpdateHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    initView();
                    break;
                case 1:
                    //   refreshView();
                    break;
                case 6://登陆后显示设定的tab页
                    int defaultPosition = tb.getDefaultSelectedTab();
                    if (defaultPosition != 0) {
                        showPageByIndex(defaultPosition);
                        //showFragment(defaultPosition);
                        tb.setCurrentTabColor(defaultPosition);
                        TabBarNew.mCurrentTabIndex = defaultPosition;
                    }

                    break;
            }

            super.handleMessage(msg);
        }
    };

    private void stopAllService() {
        //TODO 停掉MessageService
        this.stopService(new Intent(this, OSPService.class));
        this.stopService(new Intent(this, WatchService.class));
        this.stopService(new Intent(this, MessageService.class));
        this.stopService(new Intent(this, SystemInfoService.class));
        this.stopService(new Intent(this, DownLoadService.class));
    }

    //处理通过消息发送的app以及资源文件更新事件 yqs
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onShowDataEvent(UpdateResEvent event) {
        if ("appupdate".equals(event.getType())) {
            String version = event.getVersion();
            String updateNote = event.getUpdateNote();
            String url = event.getUrl();
//            Log.i(TAG, "收到app更新的消息");
            if (apkUpdateManager.checkIsNeedToDown(version)) {//如果版本不一致
                boolean isForceUpdateApk = apkUpdateManager.checkIsNeedForceDown(version);//是否需要强制升级
                apkUpdateManager.downAPK(TabBottomActivityForTalkChain.this, null, updateNote, url, apkUpdateManager, isForceUpdateApk, CheckUpdateHandler);
            }

        } else if ("appresupdate".equals(event.getType())) {
            String version = event.getVersion();
            String updateNote = event.getUpdateNote();
//            Log.i(TAG, "收到app资源更新的消息");
            final RESUpdateManager resUpdateManager = new RESUpdateManager();
            if (resUpdateManager.checkIsNeedToDown(version)) {//如果版本不一致
                apkUpdateManager.downAPPRes(TabBottomActivityForTalkChain.this, updateNote, resUpdateManager, null, CheckUpdateHandler);
            }
        }
    }

    //刷新view
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshViewEvent(RefreshViewEvent event) {
        if (event.getRefreshViewID() == RefreshViewEvent.VIEW_TABOTTOMACTIVITY) {
            // 皮肤存在，加载新皮肤
            File file = new File(SKIN_DIR, "mobile.skin");
            if (file != null && file.exists()) {
                SkinCompatManager.getInstance().loadSkin("mobile.skin", null, CustomSDCardLoader.SKIN_LOADER_STRATEGY_SDCARD);
            }
            //刷新界面
            refreshView();
        }
    }

    private void compatOpration() {
        String versionName = AppUtils.getAppVersionName();
        if ("1.0.65".equals(versionName) && !EnvironmentVariable.getProperty("compatAccount1", "").equals("true")) {
            //处理钱包
//            LogUtils.d("1.0.65恢复钱包");
            TCAccountManager tcAccountManager = new TCAccountManager(this);
            tcAccountManager.restoreChildWallet(EnvironmentVariable.getProperty("tc_ethAddress", ""), new TCAccountManager.AccountManagerListener() {
                @Override
                public void onSuccess(Object object) {
                    EnvironmentVariable.setProperty("compatAccount1", "true");
                }

                @Override
                public void onFail(String fail) {
                }
            });


//            String fileFolder = TalkChainConstant.getDataFilePath(this) + File.separator + EnvironmentVariable.getUserName();
//            File file = new File(fileFolder);
//            if (file == null) {
//                return;
//            }
//            if (!file.isDirectory()) {
//                return;
//            }
//            File[] files = file.listFiles();
//            if (files != null && files.length > 0) {
//                for (int i = 0; i < files.length; i++) {
//                    try {
//                        String text = readFile(files[i].getAbsolutePath());
//                        JSONObject jsonObject = new JSONObject(text);
//                        if (jsonObject != null && jsonObject.has("address")) {
//
//                            Account account = new AccountDao(this).getAccount("0x" + jsonObject.getString("address"));
//
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//
//                    }
//                }
//            }
        }
    }
}
